/**
 * created by zhouli on 2018/12/20
 * 只能授权
 */
import React from 'react';
import {connect} from 'react-redux';
import {Icon, Modal, Button, Form, Input, Select, Col, Row, message, Switch, Table, Badge, Popover} from 'antd';
import 'styles/permission-setting/role-permission-setting/role-permission-setting.scss';
import RPService from 'containers/permission-setting/role-permission-setting/role-permission-setting.service';
import {deepCopy, messages, isEmptyObj, trim, getSubText, superThrottle} from "share/common";
import RoleMenu from 'containers/permission-setting/components/role-menu';
import menuRoute from 'routes/menuRoute';

const Search = Input.Search;
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;
import {
  authPolicyModel,
} from 'containers/permission-setting/permission-setting.model';
//授权策略模型
let authorizationModel = deepCopy(authPolicyModel);
//授权策略类型
let authorizationTypeList = [
  {
    name: messages('common.all')/*全部*/,
    value: "ALL",
  },
  {
    name: messages('permission-setting.key81')/*部门经理*/,
    value: "DEPTMGR",
  },
  {
    name: messages('permission-setting.key33')/*部分*/,
    value: "USER",
  }
];
//授权策略类型,针对财务
let authorizationTypeListForFinance = [
  {
    name: messages('permission-setting.key33')/*部分*/,
    value: "USER",
  }
];

class RolePermissionSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalKey: '',
      loading: false,
      visible: false,
      authorization: {},
      authorizationKeyword: "",
      roleCache: null,
      cRole: {},
      data: [],
      pagination: {
        page: 0,
        total: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      columns: [
        {
          title: messages('permission-setting.key102')/*授权编码*/,
          key: "authorizationCode",
          dataIndex: 'authorizationCode',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('permission-setting.key41')/*授权策略描述*/,
          key: "authorizationDesc",
          dataIndex: 'authorizationDesc',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('permission-setting.key9')/*适用人员*/,
          key: "authorizationTypeName",
          dataIndex: 'authorizationTypeName',
          render: text => <span>{text ? <Popover placement="topLeft" content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('common.column.status')/*状态*/,
          key: 'status',
          width: '10%',
          dataIndex: 'enabled',
          render: enabled => (
            <Badge status={enabled ? 'success' : 'error'}
                   text={
                     enabled ? messages('common.status.enable') : messages('common.status.disable')
                   }/>
          )
        },
        {
          /*操作*/
          title: messages('common.operation'),
          key: "operation",
          dataIndex: 'operation',
          render: (text, record) => (
            <span>
              <a onClick={(e) => this.editItem(e, record)}>{messages('common.edit')}</a>
              <span className="ant-divider"/>
              <a onClick={(e) => this.itemDetail(e, record)}>{messages('common.detail')}</a>
            </span>)
        }
      ],
      detailUrl: menuRoute.getRouteItem('role-permission-setting-detail', 'key').url,
    }
  }

  componentDidMount() {
    if (this.props.location.state && this.props.location.state.cRole && !isEmptyObj(this.props.location.state.cRole)) {
      this.setState({
        roleCache: this.props.location.state.cRole
      })
    }
  }

  editItem = (e, record) => {
    this.showModalRole(record, true)
  };
  //跳转详情
  itemDetail = (e, record) => {
    const {cRole} = this.state;
    this.context.router.push({
      pathname: this.state.detailUrl.replace(':permissionId', record.id),
      state: {
        cRole: cRole,
      },
    });
  };
  findAuthorizationTypeName = (type) => {
    let a = type;
    authorizationTypeList.map(item => {
      if (item.value === type) {
        a = item.name;
      }
    });
    return a;
  }
  //获取角色权限列表
  getRoleAuthorizationList = () => {
    this.setState({
      loading: true
    });
    const {cRole, pagination, authorizationKeyword} = this.state;
    let params = {
      resourceId: cRole.id,
      page: pagination.page,
      size: pagination.pageSize,
      keyword: authorizationKeyword
    };

    RPService.getRoleAuthorizationList(params)
      .then(res => {
        pagination.total = Number(res.headers['x-total-count']);
        res.data.map(item => {
          item.authorizationTypeName = this.findAuthorizationTypeName(item.authorizationType)
        })
        this.setState({
          loading: false,
          data: res.data,
          pagination
        })
      })
  };

  itemSelect = (key, data) => {
    this.setState({
      cRole: (key && data) ? data : {}
    }, () => {
      if ((key && data)) {
        this.getRoleAuthorizationList();
      }
    })
  };

  //保存权限
  handleSavePermission = (e) => {
    //如果没有这个，页面会刷新
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, _values) => {
      const {authorization} = this.state;
      let values = deepCopy(_values);
      let cRole = this.state.cRole;
      values.resourcePermissionId = cRole.id;
      if (authorization.id) {
        values.id = authorization.id;
        this.updateAuthorization(values)
      } else {
        this.createAuthorization(values)
      }
    })
  };
  //新增
  createAuthorization = (authorization) => {
    this.setState({
      loading: true
    });
    RPService.createAuthorizationItem(authorization)
      .then(res => {
        this.setState({
          loading: false,
          visible: false,
        }, () => {
          this.getRoleAuthorizationList();
        })
      })
      .catch((err) => {
        this.setState({
          loading: false
        })
      })
  };
  //编辑
  updateAuthorization = (authorization) => {
    this.setState({
      loading: true
    });
    RPService.updateAuthorizationItem(authorization)
      .then(res => {
        this.setState({
          loading: false,
          visible: false,
        }, () => {
          this.getRoleAuthorizationList();
        })
      })
      .catch((err) => {
        this.setState({
          loading: false
        })
      })
  };

  // 分页点击
  onChangePager = (pag) => {
    const {pagination} = this.state;
    pagination.page = pag.current - 1;
    this.setState({
      pagination
    }, () => {
      this.getRoleAuthorizationList();
    })
  };
  //取消
  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  };
  //编辑form表单改变
  handleRoleChange = () => {
    this.setState({
      loading: false
    })
  };
  //展示模态框
  showModalRole = (_authorization, isUpdate) => {
    this.props.form.resetFields();
    let modalKey = this.state.modalKey;
    modalKey++;
    let authorization = {};
    if (isUpdate) {
      authorization = _authorization;
    } else {
      authorization = deepCopy(authorizationModel);
    }
    this.setState({
      modalKey,
      authorization,
      visible: true,
    });
  };
  onSearchListInner = () => {
    const {pagination} = this.state;
    pagination.page = 0;
    pagination.current = 1;
    this.setState({
      pagination,
    }, () => {
      this.getRoleAuthorizationList();
    })
  }
 //为了节流函数
  onInputCompnayName = (e) => {
    //这句是为了使用节流函数，不然onChangeSetUserDepName函数中只能使用上一次的输入
    this.state.authorizationKeyword = getSubText(e.target.value, 100);
    this.setState({authorizationKeyword: getSubText(e.target.value,100)});
  };
  //搜索当前角色菜单
  onSearchList = superThrottle(() => {
    this.onSearchListInner();
  }, 500, 3000);

  //渲染{messages('permission-setting.key9')/*适用人员*/}
  renderSelectOption = () => {
    return authorizationTypeList.map(item => {
      return (
        item.value !== "DEPTMGR" &&
        <Option value={item.value}>{item.name}</Option>
      )
    })
  };
  //渲染{messages('permission-setting.key9')/*适用人员*/}
  renderSelectOptionForFinance = () => {
    return authorizationTypeListForFinance.map(item => {
      return <Option value={item.value}>{item.name}</Option>
    })
  };
  //给财务角色开启数据权限
  enableDataPermission = () => {
    const {cRole} = this.state;
    const originStatus = cRole.enableDataPermission;
    let that = this;
    Modal.confirm({
      title: messages('permission-setting.key73')/*是否启用数据权限进行管控？*/,
      content: <div>
        <p><Switch defaultChecked={cRole.enableDataPermission} onChange={this.onChangeSwitch}>
          {cRole.enableDataPermission ? messages('common.status.enable') : messages('common.disabled')}
        </Switch></p>
        <p/>
        <h5>{messages('permission-setting.key74')/*1. 数据权限是在组织权限的基础上进一步限制数据范围*/}</h5>
        <h5>{messages('permission-setting.key75')/*2. 可基于某种实体的某个字段如成本中心,设置逻辑关系进行控制*/}</h5>
        <h5>{messages('permission-setting.key76')/*3. 由启用改为禁用时,已授权的数据权限将不再生效*/}</h5>
      </div>,
      onOk() {
        that.switchDataPermission();
      },
      onCancel() {
        that.onChangeSwitch(originStatus);
        that.switchDataPermission(originStatus);
      },
    });
  };
  onChangeSwitch = (val) => {
    const {cRole} = this.state;
    cRole.enableDataPermission = val;
    this.setState({
      cRole
    });
  };
  switchDataPermission = (val) => {
    const {cRole} = this.state;
    let params = {
      resourcePermissionId: cRole.id,
      enableDataPermission: val ? val : cRole.enableDataPermission
    };
    RPService.switchDataPermission(params)
      .then((res) => {
        this.setState({
          cRole: res.data
        })
      })
  };

  render() {
    const {authorization, visible, loading, data, pagination, columns, cRole, roleCache, authorizationKeyword} = this.state;
    const {getFieldDecorator} = this.props.form;
    return (
      <div className="role-permission-setting-wrap">
        <div className='left-wrap f-left'>
          <RoleMenu
            roleCache={roleCache}
            isShowEdit={false}
            onSelect={this.itemSelect}>
          </RoleMenu>
        </div>
        <div className="right-wrap">
          <div className="right-wrap-inner">
            <div className='title'>
              {cRole.permissionName}
            </div>
            <div className='btn-wrap'>
              <div className='left'>
                <Button type="primary"
                        onClick={this.showModalRole}>{messages('permission-setting.key43')/*新增授权策略*/}</Button>
                &nbsp;&nbsp;
                {cRole.permissionCategory === 'FINANCE' && <Icon type="setting" onClick={this.enableDataPermission}/>}
              </div>
            </div>
            <div className='permission-tree'>
              <div className='table-header-wrap'>
                <div className="table-header-title f-left">
                  {messages('common.total', {total: `${pagination.total}`})}
                </div>
                <div className='right f-right'>
                  <Search
                    className='right-search-inp'
                    placeholder={messages('permission-setting.key46')/*输入授权策略描述*/}
                    value={authorizationKeyword}
                    onInput={this.onInputCompnayName}
                    onChange={this.onSearchList}
                    onSearch={this.onSearchListInner}
                  />
                </div>
                <div className='clear'/>
              </div>
              <Table
                rowKey={record => record.id}
                loading={loading}
                dataSource={data}
                columns={columns}
                pagination={pagination}
                onChange={this.onChangePager}
                size="middle"
                bordered/>
            </div>
          </div>
        </div>

        <div className='clear'/>
        <div className="new-hotfix-model"/>
        <Modal
          getContainer={() => {
            return document.getElementsByClassName("new-hotfix-model")[0];
          }}
          maskClosable={false}
          closable
          width={600}
          title={authorization.id ? messages('permission-setting.key47')/*编辑授权策略*/ : messages('permission-setting.key43')/*新增授权策略*/}
          visible={visible}
          destroyOnClose={true}
          footer={null}
          onCancel={this.handleCancel}
        >
          <div className="role-modal-inner-wrap">
            <Form onChange={this.handleRoleChange}>
              <FormItem
                label={messages('permission-setting.key9')/*适用人员*/}
                colon={true}>
                {getFieldDecorator('authorizationType', {
                  initialValue: authorization.authorizationType,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.select")
                    },
                  ]
                })(
                  <Select
                    placeholder={messages("common.please.select")}
                    onChange={this.handleChange}
                  >
                    {cRole.permissionCategory === "ADMIN" && this.renderSelectOptionForFinance()}
                    {cRole.permissionCategory === "FINANCE" && this.renderSelectOptionForFinance()}
                    {cRole.permissionCategory !== "FINANCE" &&
                    cRole.permissionCategory !== "ADMIN" &&
                    this.renderSelectOption()}
                  </Select>
                )
                }
              </FormItem>
              <FormItem
                label={messages('permission-setting.key102')/*授权编码*/}
                colon={true}>
                {getFieldDecorator('authorizationCode', {
                  initialValue: authorization.authorizationCode,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                  ]
                })(
                  <Input
                    disabled={authorization.id}
                    placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>
              <FormItem
                label={messages('permission-setting.key12')/*授权描述*/}
                colon={true}>
                {getFieldDecorator('authorizationDesc', {
                  initialValue: authorization.authorizationDesc,
                  rules: []
                })(
                  <Input placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>

              <FormItem
                label={messages('common.column.status')/*状态*/}
                colon={true}>
                {getFieldDecorator("enabled", {
                  initialValue: authorization.enabled,
                  valuePropName: 'checked',
                })
                (<Switch checkedChildren={<Icon type="check"/>}
                         disabled={cRole.permissionCode === "superAdmin" && authorization.authorizationCode === "superAdmin" }
                         unCheckedChildren={<Icon type="cross"/>}/>)
                }
                {cRole.permissionCode === "superAdmin" && authorization.authorizationCode === "superAdmin" &&<div> {messages('permission-setting.key82')/*超级管理员的默认授权策略不允许修改*/}
                </div>}
              </FormItem>

              <div className="role-manage-from-footer">
                <Button onClick={this.handleCancel}>
                  {messages("common.cancel")}
                </Button>
                &nbsp;&nbsp;
                <Button type="primary"
                        onClick={this.handleSavePermission}
                        loading={loading}>
                  {messages("common.save")}
                </Button>
              </div>

            </Form>
          </div>
        </Modal>
      </div>
    )
  }
}

RolePermissionSetting.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(Form.create()(RolePermissionSetting));
